package servletPackage;

import inspur.dao.BookDao;
import inspur.dao.CookieDao;
import inspur.dao.UserDao;
import inspur.entity.BookObject;
import inspur.entity.CookieTokenObject;
import inspur.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "AuUserServlet")
public class AuUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        PrintWriter out=response.getWriter();
        String userId=request.getParameter("userId");
        if (userId==null){
            out.print("提醒，需要填写一个用户编号");
            return;
        }else{
            if (userId.equals("")){
                out.print("提醒，需要填写一个用户编号");
                return;
            }
        }
        //
        String CookieUserid= CookieDao.getCookieItemValue(request,"userid");
        if (CookieUserid==null){
            out.print("升级失败，原因：你没有登录");
        }else{

            User CookieUser= UserDao.getUserByUserId(CookieUserid);
            CookieTokenObject cto= CookieDao.CreatCookieTokenObject(request);
            User SQLmyuser=  UserDao.getUserByUserId(userId);
            boolean ctoIsOk=CookieDao.isTrueToken(cto,CookieUser.getPassword(),request);
            if (ctoIsOk&&CookieUser.getIdentity().equals("admin")){
                if (SQLmyuser.getIdentity().equals("user")||SQLmyuser.getIdentity().equals("admin")){
                    out.println("提升用户失败，原因：该用户已经是user或更高权限");
                }else{
                    User _user=UserDao.getUserByUserId(userId);
                    _user.setIdentity("user");
                    int flag=UserDao.editUser(userId,_user);
                    if (flag==2){
                        out.print("success");
                        System.out.print("success");
                    }else if(flag==3) {
                        out.print("提升用户失败，原因：用户编号重复或丢失");
                        System.out.print("3");
                    }else{
                        out.print("数据库出现未知错误，请联系管理员");
                        System.out.print("x");
                    }
                }

            }else {
                out.print("你没有权限处理这个请求，你必须是管理员才能提升受审核用户用户到user");
            }
        }
        out.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
